package com.centaline.androidsalesblog.activities.search;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.newest.NewEstDetailActivity;
import com.centaline.androidsalesblog.activities.newest.NewEstListActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateDetailActivity;
import com.centaline.androidsalesblog.activities.sale.RentListActivity;
import com.centaline.androidsalesblog.activities.sale.SaleListActivity;
import com.centaline.androidsalesblog.adapter.SearchEstTypeAdapter;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.api.sale.AutoMatchApi;
import com.centaline.androidsalesblog.base.BaseSearchActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.DefaultHint;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.businissobject.AutoMatchBo;
import com.centaline.androidsalesblog.model.businissobject.SearchEstTypeBo;
import com.centaline.androidsalesblog.model.databaseobject.ModuleDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstDo;
import com.centaline.androidsalesblog.model.databaseobject.SearchDo;
import com.centaline.androidsalesblog.model.responseobject.AutoMatchRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 首页搜索
 * Created by guilin on 16/2/19.
 */
public class SearchActivity extends BaseSearchActivity {

    private RecyclerView rv_est_type;

    private ArrayList<SearchEstTypeBo> searchEstTypeBos = new ArrayList<>();
    private SearchEstTypeAdapter searchEstTypeAdapter;

    private AutoMatchApi autoMatchApi;
    private NewEstListApi newEstListApi;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void findViews() {
        super.findViews();
        rv_est_type = (RecyclerView) findViewById(R.id.rv_est_type);
    }

    @Override
    protected void initViews() {
        super.initViews();
        rv_est_type.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        searchEstTypeAdapter = new SearchEstTypeAdapter(this, searchEstTypeBos);
        searchEstTypeAdapter.setItemOnClickListener(new RecyclerViewItemOnClickListener<SearchEstTypeBo>() {
            @Override
            public void onItemOnClick(SearchEstTypeBo searchEstTypeBo, int tag) {
                type = searchEstTypeBo.getType();
                StringBuilder hint = new StringBuilder();
                switch (searchEstTypeBo.getType()) {
                    case 10:
                        hint.append(DefaultHint.NEWESTATE.getHintText());
                        break;
                    case 20:
                    case 30:
                    case 60:
                        hint.append(DefaultHint.SALE.getHintText());
                        break;
                    default:
                        break;
                }
                setQueryHint(hint.toString());
                textChangedImmediately();
                getHistory(true);
            }
        });
        rv_est_type.setAdapter(searchEstTypeAdapter);
        initRequest();
    }

    /**
     * 初始化请求api
     */
    private void initRequest() {
        autoMatchApi = new AutoMatchApi(SearchActivity.class, AutoMatchRo.class, new IResponseListener<AutoMatchRo>() {
            @Override
            public void onResponse(AutoMatchRo autoMatchRo) {
                final ArrayList<AutoMatchBo> temp = autoMatchRo.getList();
                searchList.clear();
                if (temp == null || temp.size() == 0) {
                    if (fromUser) {
                        snack("搜索结果为空");
                    } else {
                        rv_search.setVisibility(View.GONE);
                        showHistoryLayout(true);
                    }
                } else {
                    SearchDo searchDo;
                    for (AutoMatchBo autoMatchBo : temp) {
                        searchDo = new SearchDo(type, AppConstant.CityCode);
                        searchDo.setTitle(autoMatchBo.getTagName());
                        searchDo.setCode(autoMatchBo.getTagCode());
                        searchDo.setCategory(autoMatchBo.getTagCategory());
                        searchList.add(searchDo);
                    }
                    searchAdapter.notifyDataSetChanged();
                    rv_search.setVisibility(View.VISIBLE);
                    showHistoryLayout(false);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                if (fromUser)
                    netWorkUnable();
            }
        });

        newEstListApi = new NewEstListApi(SearchActivity.class, NewEstListRo.class, new IResponseListener<NewEstListRo>() {
            @Override
            public void onResponse(NewEstListRo newEstListRo) {
                ArrayList<NewEstDo> temp = newEstListRo.getNewEstDoArrayList();
                searchList.clear();
                if (temp == null || temp.size() == 0) {
                    if (fromUser) {
                        snack("搜索结果为空");
                    } else {
                        rv_search.setVisibility(View.GONE);
                        showHistoryLayout(true);
                    }
                } else {
                    SearchDo searchDo;
                    for (NewEstDo newEstDo : temp) {
                        searchDo = new SearchDo(type, AppConstant.CityCode);
                        searchDo.setTitle(String.format(Locale.CHINA, "%s【%s】",
                                newEstDo.getAdName(), newEstDo.getEstType()));
                        searchDo.setCode(newEstDo.getEstExtId());
                        searchList.add(searchDo);
                    }
                    searchAdapter.notifyDataSetChanged();
                    rv_search.setVisibility(View.VISIBLE);
                    showHistoryLayout(false);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                if (fromUser)
                    netWorkUnable();
            }
        });
    }

    /**
     * 开始请求
     */
    private void startRequest(String query) {
        switch (type) {
            case 10:
                newEstListApi.setTitle(query);
                newEstListApi.startRequest();
                break;
            case 20:
                autoMatchApi.setType("s");
                autoMatchApi.setKey(query);
                autoMatchApi.startRequest();
                break;
            case 30:
                autoMatchApi.setType("r");
                autoMatchApi.setKey(query);
                autoMatchApi.startRequest();
                break;
            case 60:
                autoMatchApi.setType("e");
                autoMatchApi.setKey(query);
                autoMatchApi.startRequest();
                break;
            default:
                break;
        }
    }

    /**
     * 点击事件
     */
    protected void onItemClick(final SearchDo searchDo, boolean insert) {
        super.onItemClick(searchDo, insert);
        switch (searchDo.getType()) {
            case 10:
                if ("key".equals(searchDo.getCategory())) {
                    startActivity(new Intent(this, NewEstListActivity.class)
                            .putExtra(ExtraConstant.SearchContent, searchDo.getTitle()));
                } else {
                    startActivity(new Intent(this, NewEstDetailActivity.class)
                            .putExtra(ExtraConstant.NewEstId, searchDo.getCode()));
                }
                break;
            case 20:
                if ("key".equals(searchDo.getCategory())) {
                    startActivity(new Intent(this, SaleListActivity.class)
                            .putExtra(ExtraConstant.SearchContent, searchDo.getTitle()));
                } else {
                    startActivity(new Intent(this, SaleListActivity.class)
                            .putExtra(ExtraConstant.SearchObject, searchDo));
                }
                break;
            case 30:
                if ("key".equals(searchDo.getCategory())) {
                    startActivity(new Intent(this, RentListActivity.class)
                            .putExtra(ExtraConstant.SearchContent, searchDo.getTitle()));
                } else {
                    startActivity(new Intent(this, RentListActivity.class)
                            .putExtra(ExtraConstant.SearchObject, searchDo));
                }
                break;
            case 60:
                startActivity(new Intent(this, EsfEstateDetailActivity.class)
                        .putExtra(ExtraConstant.CestCode, searchDo.getCode()));
                break;
            default:
                break;
        }
    }

    @Override
    protected DefaultHint getDefaultHint() {
        initType();
        return super.getDefaultHint();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        super.onQueryTextSubmit(query);
        fromUser = true;
        if (TextUtils.isEmpty(query))
            return true;
        switch (type) {
            case 10:
                startActivity(new Intent(this, NewEstListActivity.class)
                        .putExtra(ExtraConstant.SearchContent, query));
                break;
            case 20:
                startActivity(new Intent(this, SaleListActivity.class)
                        .putExtra(ExtraConstant.SearchContent, query));
                break;
            case 30:
                startActivity(new Intent(this, RentListActivity.class)
                        .putExtra(ExtraConstant.SearchContent, query));
                break;
            case 60:
                startRequest(query);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        fromUser = false;
        if (TextUtils.isEmpty(newText)) {
            rv_search.setVisibility(View.GONE);
            showHistoryLayout(true);
        } else {
            startRequest(newText);
        }
        return true;
    }

    /**
     * 初始化搜索类型
     */
    private void initType() {
        Observable.create(new Observable.OnSubscribe<List<ModuleDo>>() {

            @Override
            public void call(Subscriber<? super List<ModuleDo>> subscriber) {
                subscriber.onNext(DataSupport.where("cityCode = ?", AppConstant.CityCode).find(ModuleDo.class));
                subscriber.onCompleted();
            }
        }).map(new Func1<List<ModuleDo>, ArrayList<SearchEstTypeBo>>() {
            @Override
            public ArrayList<SearchEstTypeBo> call(List<ModuleDo> moduleDos) {
                ArrayList<SearchEstTypeBo> temp = new ArrayList<>();
                ArrayList<Integer> typeList = new ArrayList<>();
                SearchEstTypeBo searchEstTypeBo;
                for (ModuleDo moduleDo : moduleDos) {
                    searchEstTypeBo = new SearchEstTypeBo();
                    int type = moduleDo.getType();
                    switch (type) {
                        case 10:
                            if (!typeList.contains(type)) {
                                typeList.add(type);
                                searchEstTypeBo.setType(type);
                                searchEstTypeBo.setTitle("新房");
                            }
                            break;
                        case 20:
                            if (!typeList.contains(type)) {
                                typeList.add(type);
                                searchEstTypeBo.setType(type);
                                searchEstTypeBo.setTitle("二手房");
                            }
                            break;
                        case 30:
                            if (!typeList.contains(type)) {
                                typeList.add(type);
                                searchEstTypeBo.setType(type);
                                searchEstTypeBo.setTitle("租房");
                            }
                            break;
                        case 60:
                            if (!typeList.contains(type)) {
                                typeList.add(type);
                                searchEstTypeBo.setType(type);
                                searchEstTypeBo.setTitle("小区");
                            }
                            break;
                        default:
                            break;
                    }
                    if (searchEstTypeBo.getType() != 0) {
                        temp.add(searchEstTypeBo);
                    }
                }
                return temp;
            }
        }).compose(this.<ArrayList<SearchEstTypeBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<SearchEstTypeBo>>() {
                    @Override
                    public void call(ArrayList<SearchEstTypeBo> result) {
                        searchEstTypeBos.clear();
                        searchEstTypeBos.addAll(result);
                        searchEstTypeAdapter.notifyDataSetChanged();
                        if (searchEstTypeBos.size() > 0) {
                            type = searchEstTypeBos.get(0).getType();
                            StringBuilder hint = new StringBuilder();
                            switch (type) {
                                case 10:
                                    hint.append("请输入楼盘名、板块");
                                    break;
                                case 20:
                                case 30:
                                case 60:
                                    hint.append("请输入小区、板块");
                                    break;
                                default:
                                    break;
                            }
                            setQueryHint(hint.toString());
                            getHistory(true);
                        }
                    }
                });
    }
}
